<script setup name="goods">
import { ref } from "vue"
import { useRepassword } from "@/composables/useManager"
import { useInitTable, useInitForm } from "@/composables/useCommon"
import { getGoodsList, updateGoodsStatus, createGoods, updataGoods, deleteGoods, restoreGoods, destroyGoods, checkGoods } from "@/api/goods"
import { getCategoryList } from "@/api/category"
import { useUserStore } from "@/store"
import { storeToRefs } from "pinia"
import FormDialog from "@/components/FormDialog.vue"
import ChooseImage from "@/components/ChooseImage.vue"
import Search from "@/components/Search.vue"
import SearchItem from "@/components/SearchItem.vue"
import ListHeader from "@/components/ListHeader.vue"
import Banners from "@/view/Goods/components/Banners.vue"
import Content from "@/view/Goods/components/Content.vue"
import Skus from "@/view/Goods/components/Skus.vue"

const userStore = useUserStore()
const { showSearch } = storeToRefs(userStore)
// 解构公用方法
const {
  windowHeight,
  searchForm,
  tableData,
  loading,
  currentPage,
  total,
  toast,
  limit,
  resetSearchForm,
  tableRef,
  getData,
  multiSelectionIds,
  handleSelectionChange,
  handleMultiDelete,
  handleMultiStatusChange,
  handleDelete
} = useInitTable({
  searchForm: { title: "", tab: "all", category_id: null },
  getList: getGoodsList,
  updateStatus: updateGoodsStatus,
  delete: deleteGoods,
  onGetList: res => {
    tableData.value = res.list.map(ope => {
      ope.statusLoading = false
      return ope
    })
    total.value = res.totalCount
  }
})

// 解构表单公共方法
const { form, dialogRef, formRef, rules, dialogTitle, handleSubmit, handleCreate, handleEdit, resetForm } = useInitForm({
  getData,
  updata: updataGoods,
  create: createGoods,
  form: {
    title: null, //商品名称
    category_id: null, //商品分类
    cover: null, //商品封面
    desc: null, //商品描述
    unit: "件", //商品单位
    stock: 100, //总库存
    min_stock: 10, //库存预警
    status: 1, //是否上架 0仓库1上架
    stock_display: 1, //库存显示 0隐藏1显示
    min_price: 0, //最低销售价
    min_oprice: 0 //最低原价
  },
  rules: {
    title: [
      { required: true, message: "商品名称不能为空", trigger: "blur" },
      { max: 60, message: "不能超过60个字符串", trigger: "blur" }
    ],
    category_id: [{ required: true, message: "商品分类不能为空", trigger: "blur" }],
    cover: [{ required: true, message: "商品封面不能为空", trigger: "blur" }],
    unit: [{ required: true, message: "商品单位不能为空", trigger: "blur" }],
    desc: [{ max: 150, message: "商品描述过长，请修改后重新提交", trigger: "blur" }],
    stock: [{ required: true, message: "商品总库存不能为空", trigger: "blur" }],
    status: [{ required: true, trigger: "blur" }],
    stock_display: [{ required: true, trigger: "blur" }],
    min_price: [{ required: true, message: "最低销售价不能为空", trigger: "blur" }],
    min_oprice: [{ required: true, message: "最低原价不能为空", trigger: "blur" }],
    min_stock: [{ required: true, message: "库存预警不能为空", trigger: "blur" }]
  }
})

// 获取仓库数据
const { user } = useRepassword()
// 减去头部高度、标签高度、内边距高度
let h = windowHeight.value - 64 - 44 - 36
const h2 = windowHeight.value - 64 - 44 - 184
// 设置轮播图弹窗节点
const bannersRef = ref(null)
// 商品详情弹窗节点
const contentRef = ref(null)
// 商品规格弹窗节点
const skusRef = ref(null)

// 标签页
const tabbars = [
  {
    key: "all",
    name: "全部"
  },
  {
    key: "checking",
    name: "审核中"
  },
  {
    key: "saling",
    name: "出售中"
  },
  {
    key: "off",
    name: "已下架"
  },
  {
    key: "min_stock",
    name: "库存预警"
  },
  {
    key: "delete",
    name: "回收站"
  }
]
// 获取商品分类
const category_list = ref([])
getCategoryList().then(res => (category_list.value = res))
// 打开设置轮播图弹窗
const handleGoodsBanners = row => bannersRef.value.open(row)
// 打开设置商品详情弹窗
const handleGoodsContent = row => contentRef.value.open(row)
// 打开设置商品规格
const handleGoodsSkus = row => skusRef.value.open(row)

// 审核商品
const handleCheckGoods = async (row, num) => {
  await checkGoods(row.id, { ischeck: num })
  toast("操作成功")
  getData()
}

const useMultiAction = async (func, msg) => {
  try {
    loading.value = true
    await func(multiSelectionIds.value)
    toast(`${msg}成功`)
    if (tableRef.value) {
      tableRef.value.clearSelection()
    }
    getData()
  } finally {
    loading.value = false
  }
}

// 彻底删除
const handleDestroyGoods = () => useMultiAction(destroyGoods, "彻底删除商品")
// 批量恢复
const handleRestoreGoods = () => useMultiAction(restoreGoods, "恢复商品")
</script>

<template>
  <div class="goods" :style="{ height: `${h}px` }">
    <el-tabs v-model="searchForm.tab" @tab-change="getData" type="border-card">
      <el-tab-pane :label="item.name" :name="item.key" v-for="(item, index) in tabbars" :key="index"></el-tab-pane>
      <el-card shadow="never" :body-style="{ 'padding-bottom': '10px', 'padding-left': '0', 'padding-right': '0' }">
        <Search :model="searchForm" @search="getData" @reset="resetSearchForm" @create="handleCreate">
          <SearchItem label="关键词">
            <el-input v-model="searchForm.title" placeholder="商品名称" clearable />
          </SearchItem>
          <template #show>
            <SearchItem label="商品分类">
              <el-select v-model="searchForm.category_id" placeholder="请选择商品分类" clearable>
                <el-option v-for="item in category_list" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </SearchItem>
          </template>
        </Search>

        <ListHeader create="新增商品" @create="handleCreate" @refresh="getData" CrPlacement="top" layout="create,refresh" :multiSelection="multiSelectionIds">
          <el-popconfirm
            v-if="multiSelectionIds.length && (searchForm.tab !== 'delete' || searchForm.tab == 'off')"
            width="160"
            title="是否要删除当前选择商品规格？"
            confirmButtonText="确认"
            cancelButtonText="取消"
            @confirm="handleMultiDelete"
          >
            <template #reference>
              <el-button size="small" type="danger">
                <el-icon><Close /></el-icon>
              </el-button>
            </template>
          </el-popconfirm>
          <el-tooltip effect="light" content="恢复商品" v-if="multiSelectionIds.length && (searchForm.tab === 'delete' || searchForm.tab == 'off')">
            <el-button size="small" type="success" @click="handleRestoreGoods">
              <el-icon><MagicStick /></el-icon>
            </el-button>
          </el-tooltip>
          <el-popconfirm
            v-if="multiSelectionIds.length && (searchForm.tab === 'delete' || searchForm.tab == 'off')"
            width="160"
            title="是否要从回收站中删除改商品规格？"
            confirmButtonText="确认"
            cancelButtonText="取消"
            @confirm="handleDestroyGoods"
          >
            <template #reference>
              <el-button size="small" type="danger">
                <el-icon><CloseBold /></el-icon>
              </el-button>
            </template>
          </el-popconfirm>
          <el-tooltip effect="light" content="上架" v-if="multiSelectionIds.length && (searchForm.tab == 'all' || searchForm.tab == 'off')">
            <el-button size="small" @click="handleMultiStatusChange(1)">
              <el-icon><ArrowUpBold /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip effect="light" content="下架" v-if="multiSelectionIds.length && (searchForm.tab == 'all' || searchForm.tab == 'saling')">
            <el-button size="small" @click="handleMultiStatusChange(0)">
              <el-icon><ArrowDownBold /></el-icon>
            </el-button>
          </el-tooltip>
        </ListHeader>

        <div class="card-table" :style="{ height: `${h2}px` }">
          <el-table ref="tableRef" :data="tableData" stripe style="width: 100%" v-loading="loading" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="26" />

            <el-table-column label="商品" align="center" width="266">
              <template #default="{ row }">
                <div class="goods-info">
                  <el-image :src="row.cover" fit="cover" :lazy="true" />
                  <div class="goods-info-title">
                    <p>{{ row.title }}</p>
                    <div class="goods-info-title-price">
                      <span class="min_price">￥{{ row.min_price }}</span>
                      <el-divider direction="vertical" />
                      <span>￥{{ row.min_oprice }}</span>
                    </div>
                    <p>分类:{{ row.category ? row.category.name : "未分类" }}</p>
                    <p>创建时间：{{ row.create_time }}</p>
                  </div>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="实际销量" min-width="80" prop="sale_count" align="center" />

            <el-table-column label="商品状态" min-width="80" align="center">
              <template #default="{ row }">
                <el-tag :type="row.status ? 'success' : 'danger'" size="small">{{ row.status ? "上架" : "仓库" }}</el-tag>
              </template>
            </el-table-column>

            <el-table-column label="审核状态" width="90" align="center" v-if="searchForm.tab !== 'delete'">
              <template #default="{ row }">
                <div class="status-action" v-if="row.ischeck == 0">
                  <el-button type="success" size="small" plain @click="handleCheckGoods(row, 1)">审核通过</el-button>
                  <el-button type="danger" size="small" plain @click="handleCheckGoods(row, 2)">审核拒绝</el-button>
                </div>
                <span v-else>{{ row.ischeck == 1 ? "通过" : "拒绝" }}</span>
              </template>
            </el-table-column>

            <el-table-column label="总库存" prop="stock" align="center" />

            <el-table-column label="操作" align="center">
              <template #default="{ row }">
                <div v-if="searchForm.tab !== 'delete'" class="action">
                  <el-tooltip effect="light" content="修改" placement="top">
                    <el-icon @click="handleEdit(row)"><EditPen /></el-icon>
                  </el-tooltip>
                  <el-tooltip effect="light" content="商品规格" placement="top">
                    <el-icon :class="{ active: (row.sku_type === 0 && !row.sku_value) || (row.sku_type == 1 && !row.goods_skus.length) }" @click="handleGoodsSkus(row)"><Operation /></el-icon>
                  </el-tooltip>
                  <el-tooltip effect="light" content="设置轮播图" placement="top">
                    <el-icon :class="{ active: row.goods_banner.length === 0 }" @click="handleGoodsBanners(row)"><Setting /></el-icon>
                  </el-tooltip>
                  <el-tooltip effect="light" content="商品详情" placement="top">
                    <el-icon :class="{ active: !row.content }" @click="handleGoodsContent(row)"><View /></el-icon>
                  </el-tooltip>
                  <el-popconfirm v-if="row.id !== user.id" width="200" title="是否要删除改商品规格？" confirmButtonText="确认" cancelButtonText="取消" @confirm="handleDelete([row.id])">
                    <template #reference>
                      <el-icon><CloseBold /></el-icon>
                    </template>
                  </el-popconfirm>
                </div>
                <span v-else>暂无操作</span>
              </template>
            </el-table-column>
            <template #empty>
              <el-empty description="暂无数据" :image-size="200" />
            </template>
          </el-table>

          <div class="goods-pagination">
            <el-pagination background small layout="prev, pager, next" :total="total" :current-page="currentPage" :page-size="limit" :hide-on-single-page="total < 11" @current-change="getData" />
          </div>
        </div>
        <!-- 新增商品 -->
        <FormDialog class="FormDialog" ref="dialogRef" top="7vh" :width="60" :title="dialogTitle" @submit="handleSubmit" @close="resetForm" :appendToBody="true">
          <el-form :model="form" ref="formRef" :rules="rules" label-width="94">
            <el-form-item label="商品名称" prop="title">
              <el-input v-model="form.title" placeholder="请输入商品名称，不能超过60个字符串" clearable />
            </el-form-item>
            <el-form-item label="商品封面" prop="cover">
              <ChooseImage v-model="form.cover" />
            </el-form-item>
            <el-form-item label="商品分类" prop="category_id">
              <el-select v-model="form.category_id" placeholder="请选择商品分类" clearable style="width: 100%">
                <el-option v-for="i in category_list" :key="i.id" :label="i.name" :value="i.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="商品描述" prop="desc">
              <el-input v-model="form.desc" placeholder="选填，商品卖点" clearable />
            </el-form-item>
            <el-form-item label="商品单位" prop="unit">
              <el-input v-model="form.unit" placeholder="请输入商品单位" clearable />
            </el-form-item>
            <el-form-item label="总库存" prop="stock">
              <el-input v-model="form.stock">
                <template #append>{{ form.unit }}</template>
              </el-input>
            </el-form-item>
            <el-form-item label="库存预警" prop="min_stock">
              <el-input v-model="form.min_stock">
                <template #append>{{ form.unit }}</template>
              </el-input>
            </el-form-item>
            <el-form-item label="最低销售价" prop="min_price">
              <el-input v-model="form.min_price">
                <template #append>元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="最低原价" prop="min_oprice">
              <el-input v-model="form.min_oprice">
                <template #append>元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="库存显示" prop="stock_display">
              <el-radio-group v-model="form.stock_display">
                <el-radio :label="0">隐藏</el-radio>
                <el-radio :label="1">显示</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="是否上架" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :label="0">放入仓库</el-radio>
                <el-radio :label="1">立即上架</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </FormDialog>
        <!-- 设置轮播图 -->
        <Banners class="BannersDialog" ref="bannersRef" @reload="getData" />
        <!-- 商品详情 -->
        <Content ref="contentRef" @reload="getData" />
        <!-- 商品规格 -->
        <Skus ref="skusRef" @reload="getData" />
      </el-card>
    </el-tabs>
  </div>
</template>

<style lang="scss" scoped>
.goods {
  &-info {
    display: flex;
    .el-image {
      width: 50px;
      height: 50px;
      border-radius: 4px;
      margin-right: 6px;
    }
    &-title {
      flex: 1;
      text-align-last: left;
      :nth-child(n + 2) {
        color: rgba(156, 163, 175, 1);
        font-size: 12px;
      }
      &-price {
        color: rgba(107, 114, 128, 1);
        font-size: 12px;
        .min_price {
          color: rgba(244, 63, 94, 1);
          font-size: 14px;
        }
      }
    }
  }
}
.el-card {
  border: 0;
  overflow-y: auto;
  .el-select {
    width: 100%;
  }
  .card-table {
    display: flex;
    justify-content: space-between;
    flex-direction: column;
    .el-table {
      z-index: 0;
      .status-action {
        .el-button {
          margin-left: 0;
          margin-bottom: 4px;
        }
      }
      .action {
        .active {
          color: #f46262;
        }
      }
      .el-icon {
        cursor: pointer;
        margin: 0 6px;
        &:last-child {
          margin-right: 0;
        }
      }
    }
    .goods-pagination {
      display: flex;
      justify-content: center;
      padding-top: 10px;
    }
  }
  .but-form {
    .el-button {
      margin: 2px;
      .el-icon {
        color: var(--white);
      }
    }
  }
  :deep(.choose-dialog) {
    .el-dialog__body {
      padding: 0;
    }
  }
  ::-webkit-scrollbar {
    width: 0;
  }
}
:deep(.el-tabs__content) {
  padding: 0;
}
:deep(.el-tabs__header) {
  z-index: 0;
}
:deep(.list-header) {
  .el-button {
    margin: 0 2px;
  }
}
:deep(.skus-dialog) {
  .el-dialog__body {
    padding-left: 6px;
    padding-right: 6px;
  }
}
@media screen and (max-width: 375px), screen and (max-width: 414px) {
  :deep(.list-header) {
    padding: 0 12px;
  }
  :deep(.el-dialog--center) {
    min-width: 90% !important;
  }
  .searchForm {
    padding: 0 10px;
  }
  .card-table {
    .el-table {
      .el-icon {
        margin: 0 4px !important;
        &:last-child {
          margin-right: 0;
        }
      }
    }
    .goods-pagination {
      display: flex;
      justify-content: center;
      padding-top: 10px;
    }
  }
}
</style>
